package cn.z2huo.knowledge.concurrency.virtualthread;

import cn.hutool.core.thread.ThreadUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * <p>
 *
 * @author z2huo
 */
class VirtualThreadTest {

    private static final int COUNT = 50000;

    public void virtualThreadTest() {
        ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();

        IntStream.range(0, COUNT).forEach(i -> {
            executorService.submit(() -> {
                ThreadUtil.sleep(1000);
                return i;
            });
        });

        executorService.close();
    }

    public void cacheThreadPoolPlatformThreadTest() {
        ExecutorService executorService = Executors.newCachedThreadPool();

        IntStream.range(0, COUNT).forEach(i -> {
            executorService.submit(() -> {
                ThreadUtil.sleep(1000);
                return i;
            });
        });

        executorService.close();
    }

    public void fixedThreadPoolPlatformThreadTest() {
        ExecutorService executorService = Executors.newFixedThreadPool(
                Runtime.getRuntime().availableProcessors() * 10);

        IntStream.range(0, COUNT).forEach(i -> {
            executorService.submit(() -> {
                ThreadUtil.sleep(1000);
                return i;
            });
        });

        executorService.close();
    }

    public static void main(String[] args) {
        long start, end;

        VirtualThreadTest test = new VirtualThreadTest();

        start = System.currentTimeMillis();
        test.virtualThreadTest();
        end = System.currentTimeMillis();
        System.out.println("VirtualThreadTest: " + (end - start));

        start = System.currentTimeMillis();
        test.cacheThreadPoolPlatformThreadTest();
        end = System.currentTimeMillis();
        System.out.println("cacheThreadPoolPlatformThreadTest: " + (end - start));

        start = System.currentTimeMillis();
        test.fixedThreadPoolPlatformThreadTest();
        end = System.currentTimeMillis();
        System.out.println("fixedThreadPoolPlatformThreadTest: " + (end - start));
    }
/*

COUNT = 50000 时，windows，i9 13900H
VirtualThreadTest: 1822
cacheThreadPoolPlatformThreadTest: 5178
fixedThreadPoolPlatformThreadTest: 252636


 */
}
